package com.maxjay.system.core.spring.security;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

/**
 * 访问决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源 (url或方法)
 * 
 * @author zhaixm
 *
 */
@Component("securityAccessDecisionManager")
public class SecurityAccessDecisionManager implements AccessDecisionManager {

	/**
	 * 决策核心类
	 * 
	 * @param authentication 用户登录后在SpringSecurityContext中保存的一个用户信息对象
	 * @param object 该参数是一个FilterInvocation或MethodInvocation的实例，
	 * 	如果是FilterInvocation，可以获取其url地址((FilterInvocation)object).getRequestUrl()
	 * @param configAttributes 访问指定的资源所需的角色或权限信息
	 * 
	 */
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;
		}
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
		while (ite.hasNext()) {
			ConfigAttribute ca = ite.next();
			String needRole = ((SecurityConfig) ca).getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needRole.equals(ga.getAuthority())) { // ga is user's role.
					return;
				}
			}
		}
		throw new AccessDeniedException("您无权访问");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }


}
